# -*- coding: utf-8 -*-
"""
查看测试结果 - 快速分析CSV文件

使用方法：
    python view_test_results.py storage/test_results_20251117_170000.csv
"""
import sys
import pandas as pd
from pathlib import Path

def analyze_results(csv_path):
    """分析测试结果"""
    print("=" * 60)
    print("测试结果分析")
    print("=" * 60)
    
    # 读取CSV
    df = pd.read_csv(csv_path)
    
    print(f"\n📊 文件: {csv_path}")
    print(f"📝 总测试数: {len(df)}")
    
    # 统计通过率
    passed = (df['模型返回是否正确'] == '是').sum()
    failed = (df['模型返回是否正确'] == '否').sum()
    pass_rate = passed / len(df) * 100
    
    print(f"\n✅ 通过: {passed}")
    print(f"❌ 失败: {failed}")
    print(f"📈 通过率: {pass_rate:.1f}%")
    
    # 响应时间统计
    avg_time = df['运行时间(秒)'].mean()
    min_time = df['运行时间(秒)'].min()
    max_time = df['运行时间(秒)'].max()
    
    print(f"\n⏱️  响应时间:")
    print(f"   平均: {avg_time:.2f}秒")
    print(f"   最快: {min_time:.2f}秒")
    print(f"   最慢: {max_time:.2f}秒")
    
    # 按类型分组
    normal_tests = df[df['预期输出'].str.contains('修改 parameters|修改 initial_state', na=False)]
    boundary_tests = df[df['预期输出'].str.contains('拒绝修改', na=False)]
    
    if len(normal_tests) > 0:
        normal_passed = (normal_tests['模型返回是否正确'] == '是').sum()
        print(f"\n📝 正常修改测试: {normal_passed}/{len(normal_tests)} ({normal_passed/len(normal_tests)*100:.1f}%)")
    
    if len(boundary_tests) > 0:
        boundary_passed = (boundary_tests['模型返回是否正确'] == '是').sum()
        print(f"🚫 超出范围测试: {boundary_passed}/{len(boundary_tests)} ({boundary_passed/len(boundary_tests)*100:.1f}%)")
    
    # 显示失败的测试
    failed_tests = df[df['模型返回是否正确'] == '否']
    if len(failed_tests) > 0:
        print(f"\n❌ 失败的测试 ({len(failed_tests)}个):")
        print("-" * 60)
        for idx, row in failed_tests.iterrows():
            print(f"\n{idx+1}. 用户输入: {row['用户输入']}")
            print(f"   预期输出: {row['预期输出']}")
            print(f"   模型输出: {row['模型输出'][:80]}...")
            print(f"   运行时间: {row['运行时间(秒)']}秒")
    else:
        print(f"\n🎉 所有测试都通过了！")
    
    # 显示最慢的3个测试
    print(f"\n🐌 最慢的3个测试:")
    print("-" * 60)
    slowest = df.nlargest(3, '运行时间(秒)')
    for idx, row in slowest.iterrows():
        print(f"{row['用户输入'][:40]:40s} - {row['运行时间(秒)']:.2f}秒")
    
    # 显示最快的3个测试
    print(f"\n🚀 最快的3个测试:")
    print("-" * 60)
    fastest = df.nsmallest(3, '运行时间(秒)')
    for idx, row in fastest.iterrows():
        print(f"{row['用户输入'][:40]:40s} - {row['运行时间(秒)']:.2f}秒")
    
    print("\n" + "=" * 60)


def main():
    if len(sys.argv) < 2:
        # 查找最新的测试结果文件
        storage_path = Path("storage")
        csv_files = list(storage_path.glob("test_results_*.csv"))
        
        if not csv_files:
            print("❌ 未找到测试结果文件")
            print("使用方法: python view_test_results.py <csv文件路径>")
            print("或者先运行: python batch_test_llm.py")
            return
        
        # 使用最新的文件
        csv_path = max(csv_files, key=lambda p: p.stat().st_mtime)
        print(f"📂 使用最新的测试结果: {csv_path}")
    else:
        csv_path = Path(sys.argv[1])
        
        if not csv_path.exists():
            print(f"❌ 文件不存在: {csv_path}")
            return
    
    analyze_results(csv_path)


if __name__ == "__main__":
    main()
